// -*-mode:c++; coding:utf-8-*-

#include "logger.hpp"

#include "meta_tablet_scanner.hpp"

namespace xbase
{
	meta_tablet_scanner::meta_tablet_scanner(io_service_pool &pool,
						 const endpoint_type &ep,
						 session_manager &sm,
						 const std::string &start_row,
						 const std::string &end_row)
		: base_type(pool),
		  m_io_service_pool(pool),
		  m_meta_row_ptr(new meta_row_result),
		  m_valid_row_count(0)
	{
		tablet_scan_info si(".METADATA_1ST_LEVEL", start_row, end_row);
		si.m_version_number = 1;
		si.m_num_row = 100;
		si.m_column_names.push_back("info:*");
		
		LOG(DEBUG, "scan_range: [" << start_row << "," << end_row << "]");
		
		m_tablet_scanner_ptr = tablet_scanner_ptr(new_async_module(tablet_scanner, m_io_service_pool, ep, sm, si));
	}

	void meta_tablet_scanner::on_get_next_row(handler_type handler,
		row_result::ptr_type row_ptr, const error_code &ec)
	{
		error_code e = ec;

		if(!e)
		{
			if (!m_meta_row_ptr->load(row_ptr))
			{
				e = xbase::error::bad_meta_data_row;
			}
			else
			{
				unsigned tablet_status = m_meta_row_ptr->m_tablet_info.m_status;

				if (TabletStatusGetOnline(tablet_status)
					&& !TabletStatusGetSplitting(tablet_status)
					&& !TabletStatusGetDeleted(tablet_status))
				{
					++m_valid_row_count;
				}

			}
		}

		this->get_upper_level_service().dispatch(boost::bind(handler, m_meta_row_ptr, e));
	}
}
